package edu.webtek.graven;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.webtek.cloudresp.RespLogin;

@WebServlet("/login")
public class ShopLogin extends ShopBase{
	private static final long serialVersionUID = 4968577877250477538L;
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
		if(getSessionData().isLoggedIn()){
			resp.sendRedirect("/Webtek/");
			return;
		}
		getSessionData().setMessage((String)req.getAttribute("errorMessage"));
		req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req, resp);
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
		
		String username = (String)req.getParameter("username"),
			   password = (String)req.getParameter("password");
		
		System.out.println(username);
		System.out.println(password);
		
		RespLogin login = getCloud().login(username, password);
		
		if(login.hadError()){
			System.out.println(login.getErrorString());
			doGet(req, resp);
		} else {
			SessionData data = getSessionData();
			data.setLoggedIn(true);
			data.setCustomerID(login.getCustomerID());
			data.setCustomerName(login.getCustomerName());
			data.saveData();
			doGet(req, resp);
		}
	}
}
